package hzau.utils;

import com.alibaba.fastjson.JSON;
import hzau.constants.WeChatConstant;
import hzau.pojo.User;
import hzau.pojo.WeChatTokenInfo;
import hzau.pojo.WeChatUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.swing.text.html.parser.Entity;
@Slf4j
public class WeChatUtil {
    public static WeChatUser getUserInfo(String code)throws Exception{
        HttpClient httpClient= HttpClients.createDefault();
        String tokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ WeChatConstant.APPID
                +"&secret="+WeChatConstant.APPSECRET+"&code="+code+"&grant_type=authorization_code";
        HttpGet httpGet=new HttpGet(tokenUrl);
        String responseResult="";
        HttpResponse response=httpClient.execute(httpGet);

        if(response.getStatusLine().getStatusCode()==200){
            responseResult= EntityUtils.toString(response.getEntity(),"UTF-8");

        }
        log.info("获取到token信息：{}",responseResult);
        WeChatTokenInfo tokenInfo= JSON.parseObject(responseResult,WeChatTokenInfo.class);
        String smsUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+tokenInfo.getAccessToken()+"&openid="+tokenInfo.getOpenid()+"&lang=zh_CN";
        HttpGet httpGet1=new HttpGet(smsUrl);
        HttpResponse response1= httpClient.execute(httpGet1);

        if(response1.getStatusLine().getStatusCode()==200){
            responseResult=EntityUtils.toString(response1.getEntity(),"UTF-8");
        }
        log.info("获取到个人信息：{}",responseResult);
        WeChatUser user =JSON.parseObject(responseResult,WeChatUser.class);
        return user;
    }
}
